package com.xywh.emergency_outbound.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.allenliu.badgeview.BadgeFactory;
import com.allenliu.badgeview.BadgeView;
import com.baidu.location.BDLocation;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.base.BaseLazyFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xw.repo.XEditText;
import com.xywh.emergency_outbound.R;
import com.xywh.emergency_outbound.app.EmergencyOutboundApplication;
import com.xywh.emergency_outbound.di.component.DaggerTab1Component;
import com.xywh.emergency_outbound.di.module.Tab1Module;
import com.xywh.emergency_outbound.mvp.contract.Tab1Contract;
import com.xywh.emergency_outbound.mvp.presenter.Tab1Presenter;
import com.xywh.emergency_outbound.mvp.ui.activity.ScanActivity;
import com.xywh.emergency_outbound.mvp.ui.adapter.Tab1Adapter;
import com.xywh.emergency_outbound.mvp.ui.db.entity.MaterialLocal;
import com.xywh.emergency_outbound.mvp.ui.entity.Tab1;
import com.xywh.emergency_outbound.mvp.ui.entity.Tab1Address;
import com.xywh.emergency_outbound.mvp.ui.entity.Tab4;

import org.jetbrains.annotations.NotNull;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;
import static com.jess.arms.base.BaseConstants.MAIN_CURRENT_FOUR;
import static com.jess.arms.base.BaseConstants.MAIN_CURRENT_THREE;
import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


public class Tab1Fragment extends BaseLazyFragment<Tab1Presenter> implements Tab1Contract.View, OnRefreshListener, OnLoadMoreListener, Tab1Adapter.IMaterialLocalData {

    public static final int REQUEST_WU_LIAO = 101;
    private static boolean mIsNeedDemo = true;

    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;
    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.xet_search)
    XEditText xetSearch;
    @BindView(R.id.sw_on_site)
    Switch swOnSite;
    @BindView(R.id.rl_on_site_address)
    RelativeLayout rlOnSiteAddress;
    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    @BindView(R.id.tv_address_title)
    TextView tvAddressTitle;
    @BindView(R.id.tv_address_name)
    TextView tvAddressName;
    @BindView(R.id.tv_address_phone)
    TextView tvAddressPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.rg_on_site_address)
    RadioGroup rgOnSiteAddress;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.nestedScrollView)
    NestedScrollView mNestedScrollView;
    @BindView(R.id.btn_submit_order)
    Button btnSubmitOrder;
    @BindView(R.id.img_cart)
    ImageView imgCart;
    @BindView(R.id.rl_no_address_data)
    RelativeLayout rl_no_address_data;

    private Tab1Adapter mAdapter;
    private List<Tab1.DataBean> mDataBeanList = new ArrayList<>();
    private String mid;
    private String mName;
    private Tab4.DataBean mAddressBean;
    private Tab1Address mTab1Address;
    private BadgeView badgeView;
    private boolean isRongHeQu = true;

    public static Tab1Fragment newInstance() {
        Tab1Fragment fragment = new Tab1Fragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerTab1Component //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .tab1Module(new Tab1Module(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab1, container, false);
        initToolbar(view);
        return view;
    }

    private void initToolbar(View view) {
        ToolbarUtils.initToolbarTitleNoBack(view, this, "物资调拨");
//        mBtnRight = view.findViewById(R.id.btnRight);
//        mBtnRight.setText("添加新地址");
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
        swOnSite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    isRongHeQu = true;
                    if (mTab1Address != null && mTab1Address.getData() != null && mTab1Address.getData().size() > 0) {
                        rlOnSiteAddress.setVisibility(View.VISIBLE);
                        rl_no_address_data.setVisibility(View.GONE);
                        rlAddress.setVisibility(View.GONE);
                        if (mTab1Address != null) {
                            EventBus.getDefault().post(mTab1Address.getData().get(rgOnSiteAddress.getCheckedRadioButtonId()), BaseConstants.TAB_3_RONG_HE_QU_ADDRESS);
                        }
                    } else {
                        rl_no_address_data.setVisibility(View.VISIBLE);
                        rlOnSiteAddress.setVisibility(View.GONE);
                        rlAddress.setVisibility(View.GONE);
                    }

                } else {
                    isRongHeQu = false;

                    rlOnSiteAddress.setVisibility(View.GONE);
                    rlAddress.setVisibility(View.VISIBLE);
                    if (mAddressBean == null) {
                        showMessage("请选择地址");
                        EventBus.getDefault().post("1", BaseConstants.ADDRESS_ITEM_TAG);
                        EventBus.getDefault().post(MAIN_CURRENT_FOUR, BaseConstants.SET_CURRENT_ITEM);

                    } else {
                        EventBus.getDefault().post(mAddressBean, BaseConstants.TAB_3_ADDRESS);
                    }
                }
            }
        });

        getTab1Address();

        initBadgeView();
        setImgCartNum("");
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(true);
    }

    private void initRecyclerView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        linearLayoutManager.setAutoMeasureEnabled(true);
        linearLayoutManager.setOrientation(VERTICAL);

        mRecyclerView.setLayoutManager(linearLayoutManager);
        // 设置为 true
        mRecyclerView.setHasFixedSize(true);
        // 设置为 false
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new Tab1Adapter(getActivity(), mDataBeanList, this));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Utils.navigation(getActivity(), RouterHub.SALES_CLIENT_ZUI_XIN_XIAO_XI_XIANG_QING_ACTIVITY);
            }
        });
//
        mNestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY > oldScrollY) {
                    // 向下滑动
//                    LogUtils.debugEInfo("向下滑动");
                }

                if (scrollY < oldScrollY) {
                    // 向上滑动
//                    LogUtils.debugEInfo("向上滑动");

                }

                if (scrollY == 0) {
                    // 顶部
//                    LogUtils.debugEInfo("顶部");

                }

                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    // 底部
//                    LogUtils.debugEInfo("底部");

                    if (!TextUtils.isEmpty(mid) || !TextUtils.isEmpty(mName)) {
                        getTab1Data(mid, mName);
                    }
                    mRefreshLayout.finishLoadMore();

                }
            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    private void getTab1Address() {
        mPresenter.getTab1Address(new HashMap<>());
    }

    private void initBadgeView() {
        badgeView = BadgeFactory.create(getActivity())
                .setTextColor(Color.WHITE)
                .setWidthAndHeight(25, 25)
                .setBadgeBackground(Color.RED)
                .setTextSize(10)
                .setBadgeGravity(Gravity.RIGHT | Gravity.TOP)
                .setBadgeCount(0)
                .setShape(BadgeView.SHAPE_CIRCLE)
                .setSpace(10, 10)
                .bind(imgCart);
    }

    public void setImgCartNum(String num) {

        List<MaterialLocal> materialLocalList = EmergencyOutboundApplication.getDbController().searchAll();
        if (materialLocalList != null && materialLocalList.size() >= 0) {
            badgeView.setBadgeCount(materialLocalList.size());
        }
    }

    private void getTab1Data(String mid, String mname) {
        HashMap<String, String> map = new HashMap<>();
        if (!TextUtils.isEmpty(mid)) {
            map.put("mid", mid);
        }
        if (!TextUtils.isEmpty(mname)) {
            map.put("mname", mname);
        }
        map.put("startindex", String.valueOf(mStart));
        map.put("endindex", String.valueOf(mStart + mNum - 1));
        LogUtils.debugEInfo("mid=" + mid + " mname=" + mname + " startindex=" + String.valueOf(mStart) + " endindex=" + String.valueOf(mStart + mNum - 1));
        mPresenter.getTab1Data(map);
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)}
     * 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     *
     * <p>
     * Example usage:
     *
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Subscriber(tag = "setImgCartNum", mode = ThreadMode.MAIN)
    public void setImgCartNum1(String num) {

        List<MaterialLocal> materialLocalList = EmergencyOutboundApplication.getDbController().searchAll();
        badgeView.setBadgeCount(materialLocalList.size());
    }

    @Subscriber(tag = "setAddress", mode = ThreadMode.MAIN)
    public void setAddress(BDLocation bdLocation) {

        if (bdLocation != null) {
//            tvLocation.setText(bdLocation.getAddrStr() + bdLocation.getLongitude());
            tvLocation.setText(bdLocation.getAddrStr());
        }
    }

    @Override
    public void getTab1DataSuccess(Tab1 entityData) {

        if (entityData != null && entityData.getData() != null && entityData.getData().size() > 0) {

//            mDataBeanList.clear();
//            List<MaterialLocal> materialLocals = mDbController.searchAll();
//            if (materialLocals != null && materialLocals.size() > 0) {
//
//                for (int i1 = 0; i1 < materialLocals.size(); i1++) {
//
//                    for (int i = 0; i < entityData.getData().size(); i++) {
//
//                        if (materialLocals.get(i1).getMaterialName().equals(entityData.getData().get(i).getMaterialName())
//                                && materialLocals.get(i1).getStoreName().equals(entityData.getData().get(i).getStoreName())
//                                && (materialLocals.get(i1).getStoreId() == (entityData.getData().get(i).getStoreId()))) {
//                            entityData.getData().get(i).setIsCheck(true);
//                        } else {
//                            entityData.getData().get(i).setIsCheck(false);
//                        }
//                    }
//
//                }
//
//            }
            mStart += entityData.getData().size();
            mDataBeanList.addAll(entityData.getData());
            mAdapter.notifyDataSetChanged();
            mEmptyLayout.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        } else {
//            mEmptyLayout.setVisibility(View.VISIBLE);
//            mRecyclerView.setVisibility(View.GONE);
//            showMessage("库存不足");
        }

    }

    @Override
    public void getTab1AddressSuccess(Tab1Address entityData) {
        if (entityData != null && entityData.getData() != null && entityData.getData().size() > 0) {
            mTab1Address = entityData;
            for (int i = 0; i < entityData.getData().size(); i++) {
                RadioButton view = (RadioButton) LayoutInflater.from(getActivity()).inflate(R.layout.tab1_radio_button, null);
                view.setId(i);
                if (i == 0) {
                    view.setChecked(true);
                    tvName.setText(entityData.getData().get(i).getEmgConsignee().getConsigneeName());
                    tvPhone.setText(entityData.getData().get(i).getEmgConsignee().getLinkPhone());
                }
                view.setText(entityData.getData().get(i).getAddress());
                EventBus.getDefault().post(entityData.getData().get(0), BaseConstants.TAB_3_RONG_HE_QU_ADDRESS);

                rgOnSiteAddress.addView(view);

            }
            rgOnSiteAddress.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
//                    showMessage("选择了第" + checkedId + "个，地址是：");
                    tvName.setText(entityData.getData().get(checkedId).getEmgConsignee().getConsigneeName());
                    tvPhone.setText(entityData.getData().get(checkedId).getEmgConsignee().getLinkPhone());
                    EventBus.getDefault().post(entityData.getData().get(checkedId), BaseConstants.TAB_3_RONG_HE_QU_ADDRESS);

                }
            });
            rlOnSiteAddress.setVisibility(View.VISIBLE);
            rl_no_address_data.setVisibility(View.GONE);
        } else {
            rlOnSiteAddress.setVisibility(View.GONE);
            rl_no_address_data.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

//        mRefreshLayout.finishRefresh();
//        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getContext(), message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @OnClick(R.id.img_scan)
    public void onViewClicked() {

        Intent newIntent = new Intent(getActivity(), ScanActivity.class);
        mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, REQUEST_WU_LIAO);
        startActivityForResult(newIntent, REQUEST_WU_LIAO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == REQUEST_WU_LIAO) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                mid = extras.getString(BaseConstants.SCAN_RESULT);
//                mPresenter.validateReturnInstore(this, mid);
                LogUtils.debugEInfo("扫描的数据是：" + mid);
                mDataBeanList.clear();
                mStart = 1;
                mName = "";
                getTab1Data(mid, mName);
            }

        }
    }

    @OnClick(R.id.btn_search)
    public void search() {
        if (TextUtils.isEmpty(getXetSearch())) {
            showMessage("输入物料描述查询或点击扫描物资二维码");
            return;
        }
        mDataBeanList.clear();
        mAdapter.notifyDataSetChanged();
        mStart = 1;
        mName = getXetSearch();
        getTab1Data(mid, mName);
    }

    @NotNull
    private String getXetSearch() {
        return xetSearch.getText().toString().trim();
    }

    @Override
    public void insertMaterial(Tab1.DataBean dataBean) {

        try {
            MaterialLocal materialLocal = new MaterialLocal(null, dataBean.getMaterialName(), dataBean.getStoreId(), dataBean.getStoreName(), dataBean.getMaterialUnit(), dataBean.getStoreNum(), "");
            //Add
            EmergencyOutboundApplication.getDbController().insert(materialLocal);
        } catch (Exception e) {
            e.printStackTrace();
        }

        EventBus.getDefault().post("0", BaseConstants.MATERIAL_LOCAL);
        setImgCartNum("");


//
//        List<MaterialLocal> materialLocals = mDbController.searchAll();
//
//        LogUtils.debugEInfo("materialLocals的数量是：" + materialLocals.size());

    }

    @Override
    public void delMaterial(Tab1.DataBean dataBean) {

        try {
            //Del
            EmergencyOutboundApplication.getDbController().delete(dataBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        EventBus.getDefault().post("1", BaseConstants.MATERIAL_LOCAL);
        setImgCartNum("");

//        List<MaterialLocal> materialLocals = mDbController.searchAll();
//
//        LogUtils.debugEInfo("materialLocals的数量是：" + materialLocals.size());
    }

    @Subscriber(tag = "tab1Address", mode = ThreadMode.MAIN)
    public void updateAddress(Tab4.DataBean dataBean) {
        if (dataBean != null) {
            mAddressBean = dataBean;
            tvAddressName.setText(dataBean.getConsigneeName());
            tvAddressPhone.setText(dataBean.getLinkPhone());
            tvAddress.setText(dataBean.getEmgConsigneeAddresses().get(0).getAddress());
        }

    }

    @Subscriber(tag = "updategetTab1Data", mode = ThreadMode.POST)
    public void updategetTab1Data(String msg) {
        mDataBeanList.clear();
        mAdapter.notifyDataSetChanged();
        mStart = 1;
        getTab1Data(mid, mName);

    }


    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if (!TextUtils.isEmpty(mid) || !TextUtils.isEmpty(mName)) {
            getTab1Data(mid, mName);
        }
        mRefreshLayout.finishLoadMore();

    }


    @Override
    protected void loadData() {
        super.loadData();
    }


    @OnClick({R.id.btn_submit_order, R.id.ll_cart, R.id.rl_address, R.id.rl_no_address_data, R.id.btn_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_submit_order:
                if (EmergencyOutboundApplication.getDbController().searchAll() != null && EmergencyOutboundApplication.getDbController().searchAll().size() > 0) {
                    EventBus.getDefault().post(MAIN_CURRENT_THREE, BaseConstants.SET_CURRENT_ITEM);

                } else {
                    showMessage("您还没有选择物料，请选择物料");
                }
                break;
            case R.id.ll_cart:
                EventBus.getDefault().post(MAIN_CURRENT_THREE, BaseConstants.SET_CURRENT_ITEM);

                break;
            case R.id.rl_address:
                EventBus.getDefault().post("1", BaseConstants.ADDRESS_ITEM_TAG);
                EventBus.getDefault().post(MAIN_CURRENT_FOUR, BaseConstants.SET_CURRENT_ITEM);

                break;
            case R.id.rl_no_address_data:
                getTab1Address();
                break;
            case R.id.btn_phone:

                String phone = "";

                if (isRongHeQu) {
                    phone = tvPhone.getText().toString().trim();
                } else {
                    phone = tvAddressPhone.getText().toString().trim();
                }
                if (!TextUtils.isEmpty(phone)) {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent.setData(data);
                    startActivity(intent);
                } else {
                    showMessage("请先选择应急联系人");
                }
                break;
        }
    }
}
